#!/bin/bash

PROG="$0"
ARGS="$@"
UDPPORT=6343
LOGSECS=60
CAPTURE=/var/log/sflowcapture.pcap

while [[ $# -gt 0 ]]; do
  key="$1"
  case $key in
    -p|--port)
      shift
      UDPPORT="$1"
      shift
      ;;
    -f|--file)
      shift
      CAPTURE="$1"
      shift
      ;;
    -l|--log-secs)
      shift
      LOGSECS="$1"
      shift
      ;;
    *)
      echo "Usage: $PROG [-p <port>] [-f <file>] [-l <logsecs>"]
      exit -1
      ;;
  esac
done

function run_capture() {
  startIt="$1"
  if [[ $SFTPID ]]; then
    echo "$PROG caught signal - killing sflowtool pid=SFTPID $SFTPID"
    kill -TERM "$SFTPID"
  fi
  if [ "$startIt" = "true" ]; then
    sflowtool -p "$UDPPORT" -M > "$CAPTURE" &
    SFTPID=$!
  else
    exit 1
  fi
}

trap "run_capture true" SIGHUP
trap "run_capture false" SIGTERM SIGINT
run_capture true

function shallow_sleep() {
  # A wait(1) on a background sleep(1) will terminate immediately
  # on receipt of a SIGHUP so that the trap runs right away.
  # Otherwise the the trap is only executed when the sleep is done.
  seconds="$1"
  sleep $seconds &
  pid=$!
  wait $pid
}

while true; do
  if [ "$LOGSECS" = "0" ]; then
    shallow_sleep 60
  else
    shallow_sleep "$LOGSECS"
    info=`du -h "$CAPTURE"`
    echo "$PROG $ARGS : $info"
  fi
done
